package JZOffer;

// 把字符串转换成整数
public class JzOffer67 {
    public static int strToInt(String str) {
        str = str.trim();
        if (str.length() == 0) {
            return 0;
        }
        if (!Character.isDigit(str.charAt(0)) && str.charAt(0) != '+' && str.charAt(0) != '-') {
            return 0;
        }

        StringBuilder builder = new StringBuilder();
        char ch = str.charAt(0);
        if (ch != '0') {
            builder.append(ch);
        }
        boolean isZero = !(ch > '0' && ch <= '9');
        if (str.length() > 1) {
            for (int i = 1; i < str.length(); i++) {
                if (isZero && str.charAt(i) == '0') {
                    continue;
                }
                isZero = false;
                if (!Character.isDigit(str.charAt(i))) {
                    break;
                }
                builder.append(str.charAt(i));
            }
        }
        if (builder.length() <= 1 || builder.length() > 11) {
            if (builder.length() > 10) {
                if (builder.charAt(0) == '-') {
                    return Integer.MIN_VALUE;
                }
                return Integer.MAX_VALUE;
            }
            if (builder.length() == 0) {
                return 0;
            }
            if (!Character.isDigit(builder.charAt(0))) {
                return 0;
            }
        }

        long res = 0;
        long flag = 1;
        res += builder.charAt(builder.length() - 1) - 48;
        for (int i = builder.length() - 2; i > 0; i--) {
            flag *= 10;
            if (builder.charAt(i) != '0') {
                res += (builder.charAt(i) - 48) * flag;
            }
            if (res > Integer.MAX_VALUE) {
                if (builder.charAt(0) == '-') {
                    return Integer.MIN_VALUE;
                }
                return Integer.MAX_VALUE;
            }
        }
        if (builder.charAt(0) == '-') {
            res = -res;
        } else if (builder.charAt(0) != '+' && builder.length() != 1) {
            flag *= 10;
            res += (builder.charAt(0) - 48) * flag;
        }

        return res > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) res;
    }

    public static void main(String[] args) {
        String s = "-91283472332";
        System.out.println(strToInt(s));
    }
}
